
package com.anzym.android.kegdroidkey.tasks;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;

import com.anzym.android.kegdroidkey.KegDroidListAdapter;
import com.anzym.android.kegdroidlibrary.models.KegDroid;

import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import android.content.Context;

public class FetchKegDroidTask extends AsyncTask<String, Void, ArrayList<KegDroid>> {

    private static String TAG = FetchKegDroidTask.class.getSimpleName();
    private ProgressDialog dialog = null;

    private Context mCtx;
    ArrayList<KegDroid> kdList;
    private KegDroidListAdapter kdLA;
    ListView list;

    private String kegdroidUrl = "http://kegdroidcloud.anzym.com/kegdroids/checkdrinker?gplusid=";

    public FetchKegDroidTask(Context ctx, ArrayList<KegDroid> k) {

        this.mCtx = ctx;
        this.kdList = k;
    }
    
    @Override
    protected void onPreExecute() {
        this.dialog = new ProgressDialog(mCtx);
        dialog.setMessage("Fetching KegDroids...");
        dialog.show();
        
    }

    @Override
    protected ArrayList<KegDroid> doInBackground(String... gplusids) {
        ArrayList<KegDroid> kdList = new ArrayList<KegDroid>();
        String fetchUrl = kegdroidUrl + gplusids[0];
        
        JSONObject kegDroidList = null;
        String result = "{}";
        
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(fetchUrl);
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                result = convertStreamToString(instream);
                instream.close();
            }
            kegDroidList = new JSONObject(result);
        } catch (Exception e) {
        }
        kdList = parseKegDroidList(kegDroidList);
        
        return kdList;
    }
    

    @Override
    protected void onPostExecute(ArrayList<KegDroid> result) {
        if (this.dialog.isShowing()) {
            this.dialog.dismiss();
        }
        this.kdList = result;
        Log.d(TAG, "in PostExecute result: " + result);
        Toast.makeText(mCtx, "KegDroid Fetch complete!", Toast.LENGTH_LONG).show();
    }

    private ArrayList<KegDroid> parseKegDroidList(JSONObject kdl) {
        ArrayList<KegDroid> kdArrayList = new ArrayList<KegDroid>();
       // Log.d(TAG, "Created KegDroid ArrayList");
        try {
            JSONArray kegdroids = kdl.getJSONArray("kegdroids");
            for (int i = 0; i < kegdroids.length(); i++) {
                JSONObject k = kegdroids.getJSONObject(i);
                boolean add = false;
                Log.d(TAG, "Adding KegDroid: " + k.getString("name"));
                KegDroid kDroid = new KegDroid(k.getString("name"));
                Log.d(TAG, "android_id: " + k.getString("android_id"));
                if (k.getString("android_id") != "19001") {
                    kDroid.setAndroid_id(k.getString("android_id"));
                    int[] beers = new int[2];
                    if (k.getString("beer_id_tap_zero") != "" ) {
                        beers[0] = new Integer(k.getString("beer_id_tap_zero"));
                    }
                    if (k.getString("beer_id_tap_one") != "" ) {
                        beers[1] = new Integer(k.getInt("beer_id_tap_one"));
                    }
                    kDroid.setBeer_id(beers);
                    Log.d(TAG, "LAT: " + k.getDouble("lat"));
                    kDroid.setLat(k.getDouble("lat"));
                    Log.d(TAG, "LON: " + k.getDouble("lon"));
                    kDroid.setLon(k.getDouble("lon"));
                    kDroid.setNumber_unique_beers(k.getInt("unique_beer_count"));
                    //kDroid.setNumber_unique_drinkers(k.getInt("number_unique_drinkers"));
                    
                    //kDroid.setTotal_volume_poured(k.getDouble("total_volume_poured"));
                    
                    kdArrayList.add(kDroid);
                    // Need to add last_beer, number drinks, .... 
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "kdArrayList: " + kdArrayList);
        kdList = kdArrayList;
        return kdArrayList;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

}
